<?php

/**
 * Executes all the necessary operation to upload the file in the document tool
 *
 * @author Hugues Peeters <hugues.peeters@claroline.net>
 *
 * @param  array $uploadedFile - follows the $_FILES Structure
 * @param  string $baseWorkDir - base working directory of the module
 * @param  string $uploadPath  - destination of the upload.
 *                               This path is to append to $baseWorkDir
 * @param  int $maxFilledSpace - amount of bytes to not exceed in the base
 *                               working directory
 * @param  string $uncompress  - whether 'unzip' and file is a zip;
 *                               extract the content.
 * @param string $allowPHP     - if set to true, then there is no security check for .php files
 * @return boolean : true if it succeds, false otherwise
 */

function UDADOCtreat_uploaded_file($uploadedFile, $baseWorkDir, $uploadPath, $maxFilledSpace, $uncompress= '', $allowPHP = false,$replaceFiles=false)
{	
    if ( file_upload_failed($uploadedFile) )
  	{
        $failureStr = get_file_upload_error_message($uploadedFile);
        return claro_failure::set_failure($failureStr);
    }

    if ( ! enough_size($uploadedFile['size'], $baseWorkDir, $maxFilledSpace))
    {
        return claro_failure::set_failure(get_lang('The upload has failed. There is not enough space in your directory'));
    }

    if (   $uncompress == 'unzip'
        && preg_match('/.zip$/i', $uploadedFile['name']) )
    {		
    	// UDADOC : if we don't want to replace the files, a folder will be created
		if ($replaceFiles == false)
		{
			$newDirName = str_replace(".","_",$_FILES['userFile']['name']);
			$newDirName = replace_dangerous_char(trim($newDirName."_".date('Ymdhis')));
			
			if (claro_mkdir($baseWorkDir.$uploadPath.'/'.$newDirName, CLARO_FILE_PERMISSIONS))
			{
				UDADOCupdateVisFile($uploadPath.'/'.$newDirName,'i');
				$baseWorkDir = $baseWorkDir.$uploadPath.'/'.$newDirName;
				$uploadPath = "";
			}
			else
			return claro_failure::set_failure(get_lang('File upload failed'));
		}
		
        return UDADOCtreat_secure_uploaded_file_unzip($uploadedFile, $uploadPath,
                                                $baseWorkDir, $maxFilledSpace, $allowPHP);
    }
    else
    {
        /* TRY TO ADD AN EXTENSION TO FILES WITOUT EXTENSION */
        $fileName = $uploadedFile['name'] . add_extension_for_uploaded_file($uploadedFile);

        $fileName = trim($uploadedFile['name']);

        /* CHECK FOR NO DESIRED CHARACTERS */
        $fileName = replace_dangerous_char($fileName);

        /* HANDLE DANGEROUS FILE NAME FOR SERVER SECURITY */
        $fileName = get_secure_file_name($fileName);

        /* COPY THE FILE TO THE DESIRED DESTINATION */
        if ( move_uploaded_file($uploadedFile['tmp_name'],
            $baseWorkDir.$uploadPath . '/' . $fileName) )
        {
            chmod($baseWorkDir.$uploadPath . '/' . $fileName,CLARO_FILE_PERMISSIONS);
            return $fileName;
        }
        else return claro_failure::set_failure(get_lang('File upload failed'));
    }
}



/**
 * Securely manage all the unzipping process of an uploaded document
 *
 * @author Christophe Gesch� <moosh@claroline.net>
 *
 * @param  array  $uploadedFile - follows the $_FILES Structure
 * @param  string $uploadPath   - destination of the upload.
 *                                This path is to append to $baseWorkDir
 * @param  string $baseWorkDir  - base working directory of the module
 * @param  int $maxFilledSpace  - amount of bytes to not exceed in the base
 *                                working directory
 * @param string $allowPHP     - if set to true, then there is no security check for .php files
 *
 * @return boolean true if it succeeds false otherwise
 */

function UDADOCtreat_secure_uploaded_file_unzip($uploadedFile, $uploadPath,
                                          $baseWorkDir, $maxFilledSpace,$allowPHP= false)
{
    $uploadedFileName = $uploadedFile['tmp_name'];
    return UDADOCtreat_secure_file_unzip($uploadedFileName, $uploadPath,
                                          $baseWorkDir, $maxFilledSpace,$allowPHP);
}

/**
 * unzip safly a zipfile
 *
 * @author Hugues Peeters <hugues.peeters@claroline.net>
 *
 * @param string $fileName file name of zip
 * @param string $filePath file path of zip
 * @param string $extractPath
 * @param integer $maxFilledSpace (byte) count  of byte size aivailable
 * @param boolean $allowPHP whether True the file can't contain php or phtml files
 * @return true
 * @throws claro_failure on error
 */
function UDADOCtreat_secure_file_unzip($fileName, $filePath,
                                          $extractPath, $maxFilledSpace,$allowPHP= false)
{
    $zipFile = new pclZip($fileName);

    // Check the zip content (real size and file extension)

    $zipContentArray = $zipFile->listContent();

    foreach($zipContentArray as $thisContent)
    {
        if (!$allowPHP)
        {
            if ( preg_match('~.(php.?|phtml)$~i', $thisContent['filename']))
            {
                 return claro_failure::set_failure(get_lang('The zip file can not contain .PHP files'));
            }
        }
        if (!isset($realFileSize)) $realFileSize = 0;

        $realFileSize += $thisContent['size'];
    }

    if ( ! enough_size($realFileSize, $extractPath, $maxFilledSpace) )
    {
        return claro_failure::set_failure(get_lang('The upload has failed. There is not enough space in your directory'));
    }

	$zipFile->PCLZIP_OPT_REPLACE_NEWER = true;

    $extractedFileNameList = $zipFile->extract(
        PCLZIP_OPT_PATH,        $extractPath . $filePath,
        PCLZIP_OPT_SET_CHMOD,   CLARO_FILE_PERMISSIONS
		);
		

    if ( is_array($extractedFileNameList) )
    {
        return $extractedFileNameList;
    }
    else
    {
        return false;
    }
}
?>